package com.foo.web.controller.api;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foo.common.core.domain.AjaxResult;
import com.foo.common.utils.http.HttpUtils;
import com.foo.web.core.config.NameUtil;
import com.foo.wechat.domain.WxUser;
import com.foo.wechat.service.IWxConfigService;
import com.foo.wechat.service.IWxUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("小程序登录")
@Controller
    @RequestMapping("/wechat/api/warrant")
public class WxLoginController {


    @Autowired
    private IWxUserService iWxUserService;
    @Autowired
    private IWxConfigService configService;

    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult doLogin(String code){
        JSONObject SessionKeyOpenId = getSessionKeyOrOpenId( code );
        String openId = SessionKeyOpenId.getString("openid" );
        if(openId!=null){
            WxUser user = new WxUser();
            user.setOpenid(openId);
            List<WxUser> userList = iWxUserService.selectWxUserList(user);
            if(userList.size() > 0) {
                user = userList.get(0);
                return AjaxResult.success(user);
            }else {
                WxUser wxUser = new WxUser();
                wxUser.setOpenid(openId);
                wxUser.setUserName(NameUtil.getName());
                wxUser.setUserPic("");
                iWxUserService.insertWxUser(wxUser);
                return AjaxResult.success(iWxUserService.selectWxUserByOpenId(openId));
            }
        }else {
            return AjaxResult.error("登录失败");
        }
    }

    public JSONObject getSessionKeyOrOpenId(String code) {
        //loginId=0是主程序 1是生活馆
        String key =configService.selectConfigByKey("wx_app_id");
        String secret=configService.selectConfigByKey("wx_app_secret");
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        String param = "?appid=" + key + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        //发送post请求读取调用微信接口获取openid用户唯一标识
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        JSONObject jsonObject = JSON.parseObject(HttpUtils.sendRequest( requestUrl+param,null,headers,"POST" ));
        return jsonObject;
    }



}
